<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";

import {
  ElButton,
  ElCard,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElMessageBox,
  ElOption,
  ElPagination,
  ElSelect,
  ElSpace,
  ElTable,
  ElTableColumn,
  ElTag,
} from "element-plus";

import { userApi } from "@/api/modules/user.api";
import { useCommonStore } from "@/store/common";
import {
  Delete,
  Edit,
  Lock,
  Plus,
  RefreshLeft,
  Search,
  View,
} from "@element-plus/icons-vue";
import type { IUser } from "@shared/types/user";

const commonStore = useCommonStore();
commonStore.header = "用户管理";

// 响应式数据
const loading = ref(false);
const tableData = ref<IUser[]>([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(20);

// 多选相关
const selectedUsers = ref<IUser[]>([]);
const tableRef = ref();

// 搜索条件
const searchForm = reactive({
  keyword: "",
  role: "",
  status: "",
});

// 弹窗控制
const dialogVisible = ref(false);
const dialogTitle = ref("");
const dialogType = ref<"create" | "edit" | "view">("create");

// 表单数据
const userForm = reactive<Partial<IUser>>({
  username: "",
  phone: "",
  password: "",
  role: "user",
  status: "active",
});

// 表单验证规则
const formRules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 2, max: 20, message: "用户名长度应在2-20字符之间", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "密码长度应在6-20字符之间", trigger: "blur" },
  ],
  role: [{ required: true, message: "请选择角色", trigger: "change" }],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
};

// 表单引用
const formRef = ref();

// 角色选项
const roleOptions = [
  { label: "普通用户", value: "user" },
  { label: "管理员", value: "admin" },
];

// 状态选项
const statusOptions = [
  { label: "正常", value: "active" },
  { label: "禁用", value: "disabled" },
];

// 获取角色标签类型
const getRoleType = (role: string) => {
  return role === "admin" ? "danger" : "primary";
};

// 获取角色文本
const getRoleText = (role: string) => {
  return role === "admin" ? "管理员" : "普通用户";
};

// 获取状态标签类型
const getStatusType = (status: string) => {
  return status === "active" ? "success" : "danger";
};

// 获取状态文本
const getStatusText = (status: string) => {
  return status === "active" ? "正常" : "禁用";
};

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true;
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm,
    };
    const response = await userApi.getUserList(params);
    tableData.value = response.data.data;
    total.value = response.data.total_records;
  } catch (error) {
    console.error("获取用户列表失败:", error);
    ElMessage.error("获取用户列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchUsers();
};

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    keyword: "",
    role: "",
    status: "",
  });
  handleSearch();
};

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
  fetchUsers();
};

const handleCurrentChange = (page: number) => {
  currentPage.value = page;
  fetchUsers();
};

// 多选处理
const handleSelectionChange = (selection: IUser[]) => {
  selectedUsers.value = selection;
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning("请先选择要删除的用户");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedUsers.value.length} 个用户吗？此操作不可恢复。`,
      "确认批量删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const ids = selectedUsers.value.map((user) => user._id!);
    await userApi.batchDeleteUser(ids);
    ElMessage.success(`成功删除 ${selectedUsers.value.length} 个用户`);

    // 清空选择并刷新数据
    selectedUsers.value = [];
    tableRef.value?.clearSelection();
    fetchUsers();
  } catch (error) {
    if (error !== "cancel") {
      console.error("批量删除用户失败:", error);
      ElMessage.error("批量删除用户失败");
    }
  }
};

// 打开弹窗
const openDialog = (type: "create" | "edit" | "view", user?: IUser) => {
  dialogType.value = type;
  dialogVisible.value = true;

  if (type === "create") {
    dialogTitle.value = "创建用户";
    Object.assign(userForm, {
      username: "",
      phone: "",
      password: "",
      role: "user",
      status: "active",
    });
  } else if (type === "edit" && user) {
    dialogTitle.value = "编辑用户";
    Object.assign(userForm, { ...user, password: "" }); // 编辑时不显示密码
  } else if (type === "view" && user) {
    dialogTitle.value = "用户详情";
    Object.assign(userForm, { ...user });
  }
};

// 关闭弹窗
const closeDialog = () => {
  dialogVisible.value = false;
  formRef.value?.resetFields();
};

// 保存用户
const handleSave = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    if (dialogType.value === "create") {
      // 确保必填字段存在
      const createData = {
        username: userForm.username!,
        phone: userForm.phone!,
        password: userForm.password!,
        role: userForm.role!,
        status: userForm.status!,
      };
      await userApi.createUser(createData);
      ElMessage.success("用户创建成功");
    } else {
      await userApi.updateUser({ id: userForm._id!, ...userForm });
      ElMessage.success("用户更新成功");
    }

    closeDialog();
    fetchUsers();
  } catch (error) {
    console.error("保存用户失败:", error);
    ElMessage.error("保存用户失败");
  }
};

// 删除用户
const handleDelete = async (user: IUser) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户"${user.username}"吗？此操作不可恢复。`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    await userApi.deleteUser(user._id!);
    ElMessage.success("用户删除成功");
    fetchUsers();
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除用户失败:", error);
      ElMessage.error("删除用户失败");
    }
  }
};

// 重置密码
const handleResetPassword = async (user: IUser) => {
  try {
    const { value: newPassword } = await ElMessageBox.prompt(
      "请输入新密码",
      "重置密码",
      {
        inputType: "password",
        inputPattern: /.{6,}/,
        inputErrorMessage: "密码长度不能少于6位",
      }
    );

    await userApi.resetPassword(user._id!, newPassword);
    ElMessage.success("密码重置成功");
  } catch (error) {
    if (error !== "cancel") {
      console.error("重置密码失败:", error);
      ElMessage.error("重置密码失败");
    }
  }
};

// 切换用户状态
const handleToggleStatus = async (user: IUser) => {
  const newStatus = user.status === "active" ? "disabled" : "active";
  const action = newStatus === "active" ? "启用" : "禁用";

  try {
    await ElMessageBox.confirm(`确定${action}此用户吗？`, `确认${action}`, {
      type: "warning",
    });

    await userApi.updateUser({
      id: user._id!,
      status: newStatus,
    });

    ElMessage.success(`用户${action}成功`);
    fetchUsers();
  } catch (error) {
    if (error !== "cancel") {
      console.error(`${action}用户失败:`, error);
      ElMessage.error(`${action}用户失败`);
    }
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchUsers();
});
</script>

<template>
  <div class="user-page">
    <!-- 搜索区域 -->
    <ElCard class="search-card">
      <div class="search-form">
        <ElSpace wrap>
          <ElInput
            v-model="searchForm.keyword"
            placeholder="搜索用户名或手机号"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <Search />
            </template>
          </ElInput>

          <ElSelect
            v-model="searchForm.role"
            placeholder="选择角色"
            clearable
            style="width: 120px"
          >
            <ElOption
              v-for="option in roleOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </ElSelect>

          <ElSelect
            v-model="searchForm.status"
            placeholder="选择状态"
            clearable
            style="width: 120px"
          >
            <ElOption
              v-for="option in statusOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </ElSelect>

          <ElButton type="primary" :icon="Search" @click="handleSearch">
            搜索
          </ElButton>

          <ElButton @click="handleReset"> 重置 </ElButton>

          <ElButton type="primary" :icon="Plus" @click="openDialog('create')">
            创建用户
          </ElButton>

          <ElButton
            type="danger"
            :icon="Delete"
            :disabled="selectedUsers.length === 0"
            @click="handleBatchDelete"
          >
            批量删除 ({{ selectedUsers.length }})
          </ElButton>
        </ElSpace>
      </div>
    </ElCard>

    <!-- 表格区域 -->
    <ElCard class="table-card">
      <ElTable
        ref="tableRef"
        :data="tableData"
        :loading="loading"
        stripe
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <ElTableColumn type="selection" width="55" />

        <ElTableColumn prop="username" label="用户名" :width="100" />

        <ElTableColumn prop="phone" label="手机号" :width="200" />

        <ElTableColumn prop="role" label="角色" :width="100">
          <template #default="{ row }">
            <ElTag :type="getRoleType(row.role)">
              {{ getRoleText(row.role) }}
            </ElTag>
          </template>
        </ElTableColumn>

        <ElTableColumn prop="status" label="状态" :width="100">
          <template #default="{ row }">
            <ElTag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </ElTag>
          </template>
        </ElTableColumn>

        <ElTableColumn prop="create_time" label="创建时间">
          <template #default="{ row }">
            {{ new Date(row.create_time).toLocaleString() }}
          </template>
        </ElTableColumn>

        <ElTableColumn label="操作">
          <template #default="{ row }">
            <ElSpace>
              <ElButton
                type="primary"
                size="small"
                :icon="View"
                @click="openDialog('view', row)"
              >
                查看
              </ElButton>

              <ElButton
                type="primary"
                size="small"
                :icon="Edit"
                @click="openDialog('edit', row)"
              >
                编辑
              </ElButton>

              <ElButton
                type="warning"
                size="small"
                :icon="Lock"
                @click="handleResetPassword(row)"
              >
                重置密码
              </ElButton>

              <ElButton
                size="small"
                :type="row.status === 'active' ? 'danger' : 'success'"
                :icon="RefreshLeft"
                @click="handleToggleStatus(row)"
              >
                {{ row.status === "active" ? "禁用" : "启用" }}
              </ElButton>

              <ElButton
                type="danger"
                size="small"
                :icon="Delete"
                @click="handleDelete(row)"
              >
                删除
              </ElButton>
            </ElSpace>
          </template>
        </ElTableColumn>
      </ElTable>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <ElPagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </ElCard>

    <!-- 创建/编辑弹窗 -->
    <ElDialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
      @close="closeDialog"
    >
      <ElForm
        ref="formRef"
        :model="userForm"
        :rules="formRules"
        label-width="100px"
        :disabled="dialogType === 'view'"
      >
        <ElFormItem label="用户名" prop="username">
          <ElInput
            v-model="userForm.username"
            placeholder="请输入用户名"
            maxlength="20"
            show-word-limit
          />
        </ElFormItem>

        <ElFormItem label="手机号" prop="phone">
          <ElInput
            v-model="userForm.phone"
            placeholder="请输入手机号"
            maxlength="11"
          />
        </ElFormItem>

        <ElFormItem v-if="dialogType === 'create'" label="密码" prop="password">
          <ElInput
            v-model="userForm.password"
            type="password"
            placeholder="请输入密码"
            maxlength="20"
            show-password
          />
        </ElFormItem>

        <ElFormItem label="角色" prop="role">
          <ElSelect v-model="userForm.role" style="width: 100%">
            <ElOption
              v-for="option in roleOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </ElSelect>
        </ElFormItem>

        <ElFormItem label="状态" prop="status">
          <ElSelect v-model="userForm.status" style="width: 100%">
            <ElOption
              v-for="option in statusOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </ElSelect>
        </ElFormItem>
      </ElForm>

      <template #footer v-if="dialogType !== 'view'">
        <ElSpace>
          <ElButton @click="closeDialog">取消</ElButton>
          <ElButton type="primary" @click="handleSave">保存</ElButton>
        </ElSpace>
      </template>
    </ElDialog>
  </div>
</template>

<style scoped>
.user-page {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: center;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 批量删除按钮样式 */
.el-button--danger[disabled] {
  opacity: 0.6;
}
</style>
